import { Input, Button, Form, message } from "antd";
import type { FormProps } from "antd";
import SvgIcon from "@/components/SvgIcon";
import { Link, useNavigate } from "react-router-dom";
import { useState } from "react";
import SetUserInfo from "@/components/SetUserInfo";
import type { RegisterInfo, RegisterUserInfo } from "@/api/xhr/user/type";
import { setStoreItem } from "@/util/storage";
import { register, checkEmailExists } from "@/api/xhr/user/index";
import EmailVerifyModal from "@/components/EmailVerifyModal";
import "./index.css";

const Register = () => {
  const navigate = useNavigate();
  const initialValues: RegisterUserInfo = {
    email: "",
    username: "",
    avatar: "http://imgfile.xxkdjy.top/2024013116291818691.jpg",
    sex: 1,
    userSignature: ""
  };
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [emailVerifyVisible, setEmailVerifyVisible] = useState(false);
  const [pendingUserInfo, setPendingUserInfo] = useState<RegisterUserInfo | null>(null);

  async function toReagister(userInfo: RegisterUserInfo) {
    // 验证邮箱唯一性
    try {
      const res = await checkEmailExists(userInfo.email);
      if (res.data?.exists) {
        message.error("该邮箱已被注册，请更换邮箱");
        return;
      }
      
      // 设置待验证的用户信息
      setPendingUserInfo(userInfo);
      
      // 如果有邮箱，打开验证码模态框
      if (userInfo.email) {
        setEmailVerifyVisible(true);
      } else {
        // 没有邮箱，直接注册
        executeRegister(userInfo);
      }
    } catch (error) {
      console.error("验证邮箱失败:", error);
    }
  }
  
  // 执行注册
  const executeRegister = async (userInfo: RegisterUserInfo, verifyCode?: string) => {
    setConfirmLoading(true);
    const userAuth: RegisterInfo = form.getFieldsValue(true);
    const params: RegisterUserInfo & RegisterInfo = {
      ...userInfo,
      ...userAuth
    };
    
    // 如果提供了验证码，添加到请求中
    if (verifyCode) {
      params.verifyCode = verifyCode;
    }
    
    try {
      const res = await register(params);
      const userinfo = res.data;
      setStoreItem(
        "userPassword",
        {
          userAccount: userinfo.userAccount,
          password: userinfo.password
        },
        true
      );
      setOpen(false);
      navigate("/login");
    } catch (error) {
      console.error("注册失败:", error);
      message.error("注册失败，请稍后重试");
    } finally {
      setConfirmLoading(false);
    }
  };
  
  // 验证码验证成功
  const handleVerifySuccess = () => {
    setEmailVerifyVisible(false);
    if (pendingUserInfo) {
      // 验证通过后继续注册流程
      executeRegister(pendingUserInfo);
    }
  };
  
  // 验证码取消
  const handleVerifyCancel = () => {
    setEmailVerifyVisible(false);
    setPendingUserInfo(null);
    setConfirmLoading(false);
  };
  
  const onFinish: FormProps<RegisterInfo>["onFinish"] = () => {
    setOpen(true);
  };
  
  return (
    <>
      <div className="h-full flex flex-col justify-center box-border p-[20px]">
        <div className="text-left">
          <span className="text-4xl text-cyan-400">X</span>
          聊天室
        </div>
        <div className="flex items-center justify-around">
          <SvgIcon name="login" className="h-96 w-96"></SvgIcon>
          <div className="p-5 text-left box-border">
            <h1 className="mb-2 text-[30px] font-medium text-zinc-900">
              欢迎来到X聊天室
            </h1>
            <p className="mb-7 text-neutral-700 text-xs">
              注册账号，开始你的聊天之旅
            </p>
            <Form onFinish={onFinish} autoComplete="off" form={form}>
              <div className="login-input">
                <div className="px-3 py-2 flex items-center hover:bg-[#7575750d]">
                  <SvgIcon
                    name="username"
                    className="h-[24px] w-[24px]"
                  ></SvgIcon>
                  <div className="ml-2 text-xs">
                    <div className="text-xs text-left text-[#666]">账号:</div>
                    <Form.Item<RegisterInfo>
                      className="mb-0"
                      name="userAccount"
                      rules={[
                        {
                          required: true,
                          message: "请输入你的账号!"
                        }
                      ]}
                    >
                      <Input
                        allowClear
                        size="small"
                        variant="borderless"
                        className="border-0 p-0"
                      />
                    </Form.Item>
                  </div>
                </div>
                <div className="px-3 py-2 flex items-center hover:bg-[#7575750d]">
                  <SvgIcon
                    name="password"
                    className="h-[24px] w-[24px]"
                  ></SvgIcon>
                  <div className="ml-2 text-xs">
                    <div className="text-xs text-left text-[#666]">密码:</div>
                    <Form.Item<RegisterInfo>
                      className="mb-0 relative"
                      name="password"
                      rules={[
                        { required: true, message: "把你的密码放进输入框里!" },
                        { min: 6, message: "密码至少6位!" },
                        { max: 10, message: "密码最长10位!" }
                      ]}
                    >
                      <Input.Password
                        allowClear
                        size="small"
                        variant="borderless"
                        className="border-0 p-0"
                      />
                    </Form.Item>
                  </div>
                </div>
                <div className="px-3 py-2 flex items-center hover:bg-[#7575750d]">
                  <SvgIcon
                    name="password"
                    className="h-[24px] w-[24px]"
                  ></SvgIcon>
                  <div className="ml-2 text-xs">
                    <div className="text-xs text-left text-[#666]">
                      确认密码:
                    </div>
                    <Form.Item<RegisterInfo>
                      className="mb-0"
                      name="confirmPassword"
                      rules={[
                        {
                          required: true,
                          message: "请再次输入你的密码!"
                        },
                        ({ getFieldValue }) => ({
                          validator(_, value) {
                            if (!value || getFieldValue("password") === value)
                              return Promise.resolve();
                            return Promise.reject(
                              new Error("两次输入的密码不一致!")
                            );
                          }
                        })
                      ]}
                    >
                      <Input.Password
                        allowClear
                        size="small"
                        variant="borderless"
                        className="border-0 p-0"
                      />
                    </Form.Item>
                  </div>
                </div>
              </div>
              <div className="px-3 text-xs flex justify-between items-center my-1 text-[#666]">
                <Link to={"/login"}>
                  <span className="cursor-pointer">已有密码去登录</span>
                </Link>
              </div>
              <div className="my-7 text-xs flex items-center text-[#666]">
                <Form.Item
                  wrapperCol={{
                    offset: 8,
                    span: 16
                  }}
                >
                  <Button shape="round" type="primary" htmlType="submit">
                    注册
                  </Button>
                </Form.Item>
              </div>
            </Form>
          </div>
        </div>
      </div>
      <SetUserInfo
        showCancel={setOpen}
        open={open}
        initialValues={initialValues}
        callback={toReagister}
        confirmLoading={confirmLoading}
      ></SetUserInfo>
      
      {/* 邮箱验证码Modal */}
      {pendingUserInfo && (
        <EmailVerifyModal
          open={emailVerifyVisible}
          email={pendingUserInfo.email}
          onCancel={handleVerifyCancel}
          onSuccess={handleVerifySuccess}
          type="register"
        />
      )}
    </>
  );
};

export default Register;
